/**
 * Created by admin on 2016/8/17.
 */
var assert = require('../assert');

// 获取指定用户的地址
exports.getAddress = function (req, res) {
    var userId = req.query.userId;
    if (!userId){
        res.send(assert.response_sms(400, '参数不能为空'));
        return;
    }
    var User = Parse.Object.extend('User');
    var user = new User();
    user.id = userId;
    var query = new Parse.Query('OPAddress');
    query.equalTo('user', user);
    query.find().then(function (addresses) {
        res.send(assert.response_sms(200, '获取地址成功', addresses))
    }, function (error) {
        res.send(assert.response_sms(400, '获取地址出错', error.message))
    })
};

exports.getAddressInfo = function (req,res) {
    var addressId = req.params.addressId;
    if(!addressId){
        res.send(assert.response_sms(400, '参数不能为空'));
        return;
    }
    var query = new Parse.Query("OPAddress");
    query.get(addressId).then(function (address) {
        if(address){
            res.send(assert.response_sms(200, '获取地址成功', address));
        }else{
            res.send(assert.response_sms(302,'未找到对应的地址信息'));
        }
    }, function (err,error) {
        res.send(assert.response_sms(101,"查询错误"));
    })
};

// 添加一个有效的地址
exports.postAddress = function (req, res) {
    var userId = req.body.userId;
    var city = req.body.city;
    var tel = req.body.tel;
    var username = req.body.username;
    var isDefault = req.body.isDefault;
    var detailAddress = req.body.address;
    var hasNull = assert.check_parms([userId, city, tel, detailAddress, username]);
    if (hasNull){
        res.send(assert.response_sms(400, '参数不能为空'));
        return
    }
    // 转换isDefault
    if (isDefault == 'false'){
        isDefault = false;
    }else if (isDefault == 'true'){
        isDefault = true;
    }else {
        res.send(assert.response_sms(400, 'isDefault参数错误'));
        return
    }
    // 创建user，address
    var User = Parse.Object.extend('User');
    var user = new User();
    user.id = userId;
    var Address = Parse.Object.extend('OPAddress');
    var address = new Address();
    address.set('user', user);
    address.set('city', city);
    address.set('tel', tel);
    address.set('address', detailAddress);
    address.set('name', username);
    address.set('isDefault', isDefault);
    // 如果isDefault是true,那么把之前的默认地址改为false，在保存
    if (isDefault){
        var query = new Parse.Query('OPAddress');
        query.equalTo('user', user);
        query.equalTo('isDefault', true);
        query.find().then(function (result) {
            for (var i=0; i<result.length; i++){
                result[i].set('isDefault', false);
                result[i].save();
            }
        }, function (error) {
        //    没有找到相应的订单
        })
    }
    address.save().then(function (result) {
        res.send(assert.response_sms(200, '添加地址成功', result));
    }, function (error) {
        res.send(assert.response_sms(400, '添加地址失败'));
    });
};

exports.kdAddressInfo = function (req,res) {
    var addressId = req.params.addressId;
    if(!addressId){
        res.json(assert.con2json(101, '参数不能为空'));
        return;
    }
    var query = new Parse.Query("OPAddress");
    query.get(addressId).then(function (address) {
        if(address){
            res.json(assert.con2json(200, '获取地址成功', address));
        }else{
            res.json(assert.con2json(302,'未找到对应的地址信息'));
        }
    }, function (err,error) {
        res.send(assert.con2json(400,"查询错误"));
    })
};


// 设置默认地址
exports.setDefaultAddress = function (req, res) {
    var userId = req.body.userId;
    var addressId = req.body.addressId;
    console.log(addressId);
    if (!(userId && addressId)){
        res.send(assert.response_sms(400, '参数不能为空'));
        return
    }
    var query = new Parse.Query('OPAddress');
    var User =  Parse.Object.extend('User');
    var user = new User();
    user.id = userId;
    query.equalTo('user', user);
    query.equalTo('isDefault', true);
    query.first().then(function (address) {
        if (address){
            address.set('isDefault', false);
            return address.save();
        }
        var addressQuery = new Parse.Query('OPAddress');
        addressQuery.get(addressId).then(function (address) {
            address.set('isDefault', true);
            address.save().then(function (result) {
                res.send(assert.response_sms(200, '设置成功'))
            }, function (error) {
                res.send(assert.response_sms(400, '设置失败'));
                console.log(error.message);
            });
        }, function (error) {
            res.send(assert.response_sms(402, '设置失败'));
            console.log(error.message);
        });
    }, function (error) {
        res.send(assert.response_sms(402, '查询已有的地址失败'));
    }).then(function (result) {
        console.log('成功将之前的地址isDefault设置为false');
        var addressQuery = new Parse.Query('OPAddress');
        addressQuery.get(addressId).then(function (address) {
            address.set('isDefault', true);
            address.save().then(function (result) {
                res.send(assert.response_sms(200, '设置成功'))
            }, function (error) {
                res.send(assert.response_sms(400, '设置失败'));
                console.log(error.message);
            });
        }, function (error) {
            res.send(assert.response_sms(402, '设置失败'));
            console.log(error.message);
        });
    }, function (error) {
        res.send(assert.response_sms(402, '设置失败'));
    });
};

exports.deleteAddress = function (req, res) {
    var addressId = req.params.addressId;
    if (!addressId){
        res.send(assert.response_sms(400, '参数不能为空'));
        return
    }
    var query = new Parse.Query('OPAddress');
    query.get(addressId).then(function (address) {
        return address.destroy()
    }, function (error) {
        res.send(assert.response_sms(400, '没有查找到相关地址'));
    }).then(function (result) {
        res.send(assert.response_sms(200, '删除地址成功', result));
    }, function (error) {
        res.send(assert.response_sms(400, '删除地址失败'));
    })
};

exports.editAddress = function (req, res) {
    var addressId = req.params.addressId;
    var city = req.body.city;
    var tel = req.body.tel;
    var username = req.body.name;
    var addressStr = req.body.address;
    var hasNull = assert.check_parms([addressId, city, tel, addressStr, username]);
    if (hasNull){
        res.send(assert.response_sms(400, '参数不能为空'));
        return
    }
    var query = new Parse.Query('OPAddress');
    query.get(addressId).then(function (address) {
        address.set('city', city);
        address.set('tel', tel);
        address.set('name', username);
        address.set('address', addressStr);
        address.save().then(function (modRes) {
            if(modRes){
                res.send(assert.response_sms(200, '修改地址成功'));
            }else{
                res.send(assert.response_sms(400, '修改地址失败'));
            }
        }, function (err,error) {
            res.send(assert.response_sms(500, '修改地址失败'));
        });
    }, function (error) {
        res.send(assert.response_sms(400, '查找地址失败'));
    });
};
// 获取默认地址
exports.getDefaultAddress = function (req, res) {
    var userId = req.query.userId;
    if (!userId){
        res.send(assert.response_sms(401, '参数为空'));
        return
    }
    // 创建user对象
    var User = Parse.Object.extend('User');
    var user = new User();
    user.id = userId;
    // 创建查询对象
    var query = new Parse.Query('OPAddress');
    query.equalTo('user', user);
    query.equalTo('isDefault', true);
    query.first().then(function (address) {
        if (address){
            res.send(assert.response_sms(200, '成功获取', address));
        }else {
            res.send(assert.response_sms(201, '还没有设置默认地址'));
        }
    }, function (error) {
        res.send(assert.response_sms(400, '获取失败'));
        console.log(error.message);
    })
};

//********************************************************************************************

// 添加一个有效的地址(kd微店)
exports.createKDAddress = function (req, res) {
    console.log(req.body);
    var userId = req.body.userId;
    var province = req.body.province;
    var city = req.body.city;
    var district = req.body.district;
    var tel = req.body.tel;
    var username = req.body.username;
    var detailAddress = req.body.detailAddress;
    var postcode = req.body.postcode;
    var hasNull = assert.check_parms([userId, province, city, district, tel, detailAddress, username]);
    if (hasNull){
        res.json(assert.con2json(101, '参数不能为空'));
        return;
    }
    // 创建user，address
    var User = Parse.Object.extend('User');
    var user = new User();
    user.id = userId;

    var Address = Parse.Object.extend('OPAddress');
    var address = new Address();
    address.set('user', user);
    address.set('province', province);
    address.set('city', city);
    address.set('district', district);
    address.set('tel', tel);
    address.set('address', detailAddress);
    address.set('name', username);
    address.set('postcode', postcode);
    address.save().then(function (result) {
        res.json(assert.con2json(200, '添加地址成功', assert.obj2dic(result, ['province', 'city', 'district', 'tel', 'address', 'name', 'postcode'])));
    }, function (error) {
        res.json(assert.con2json(400, '添加地址失败'));
    });
};
// 修改一个地址
exports.editKDAddress = function (req, res) {
    var addressId = req.params.id;
    var province = req.body.province;
    var city = req.body.city;
    var district = req.body.district;
    var tel = req.body.tel;
    var username = req.body.username;
    var detailAddress = req.body.detailAddress;
    var postcode = req.body.postcode;
    var hasNull = assert.check_parms([addressId, province, city, district, tel, detailAddress, username]);
    if (hasNull){
        res.json(assert.con2json(101, '参数不能为空'));
        return;
    }
    // 创建user，address
    var query = new Parse.Query('OPAddress');
    query.get(addressId).then(function (address) {
        address.set('province', province);
        address.set('city', city);
        address.set('district', district);
        address.set('tel', tel);
        address.set('address', detailAddress);
        address.set('name', username);
        address.set('postcode', postcode);
        address.save().then(function (modRes) {
            if(modRes){
                res.json(assert.con2json(200, '修改地址成功', assert.obj2dic(modRes, ['province', 'city', 'district', 'tel', 'address', 'name', 'postcode'])));
            }else{
                res.json(assert.con2json(400, '修改地址失败'));
            }
        }, function (err,error) {
            res.json(assert.con2json(500, '修改地址失败'));
        });
    }, function (error) {
        res.json(assert.con2json(400, '查找地址失败'));
    });
};
// 获取kd微店地址
exports.getKDAddress = function (req, res) {
    var userId = req.query.userId;
    if (!userId){
        res.json(assert.con2json(400, '参数不能为空'));
        return;
    }
    var User = Parse.Object.extend('User');
    var user = new User();
    user.id = userId;
    var query = new Parse.Query('OPAddress');
    query.select('province', 'city', 'district', 'tel', 'address', 'name', 'postcode');
    query.equalTo('user', user);
    query.find().then(function (addresses) {
        var temp = [];
        addresses.forEach(function (item) {
            if (typeof item.get('postcode') != 'undefined'){
                item = assert.obj2dic(item, ['province', 'city', 'district', 'tel', 'address', 'name', 'postcode']);
                temp.push(item);
            }
        });
        res.json(assert.con2json(200, '获取地址成功', temp))
    }, function (error) {
        res.json(assert.con2json(400, '获取地址出错', error.message))
    })
};